<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import html2canvas from 'html2canvas';
import axios from 'axios';
import jsPDF from 'jspdf';
//@ts-ignore
const virtuaListDOM = ref<InstanceType<typeof VituaList> | null>(null)
const isLoading = ref(true) // 添加加载状态
const router = useRouter()
const courses = ref([])
const getcourses = async () => {
  try {
    const res = await axios.get('http://localhost:3000/courses')
    courses.value = res.data.data
  } catch (err) {
    console.error('获取课程数据失败:', err)
  } finally {
    isLoading.value = false
  }
}
const handleClickData=(data:any)=>{// 接收子组件的数据
  console.log(data)
  axios.delete(`http://localhost:3000/courses/${data.id}`).then((res) => {
    console.log(res)
    getcourses()
  })
  
}


// 导出图片
const handleClick = () => {
  const renderDOM = virtuaListDOM?.value?.$el
  html2canvas(renderDOM).then(canvas => {
    const base64 = canvas.toDataURL('image/png')
    const a = document.createElement('a')
    a.href = base64
    a.download = 'test.png'
    const me = new MouseEvent('click')
    a.dispatchEvent(me)
  })
}
const exportpdf = async () => {
    const renderDom = virtuaListDOM?.value?.$el;
    html2canvas(renderDom).then(canvas => {// 导出图片
        const imgData = canvas.toDataURL('image/jpeg', 1.0);// 图片转base64
        const pdf = new jsPDF('p', 'mm', 'a4');// 创建一个PDF对象,p代表纵向，mm代表单位为mm，a4代表纸张大小
        // 计算图片宽高适配A4
        const pageWidth = pdf.internal.pageSize.getWidth();// 获取A4纸张宽度
        const pageHeight = pdf.internal.pageSize.getHeight();// 获取A4纸张高度
        // 以宽度为基准等比缩放
        const imgProps = {
            width: canvas.width,// 图片宽度
            height: canvas.height
        };
        const ratio = Math.min(pageWidth / imgProps.width, pageHeight / imgProps.height);// 计算缩放比例
        const imgWidth = imgProps.width * ratio;// 缩放后的图片宽度
        const imgHeight = imgProps.height * ratio;// 缩放后的图片高度
        pdf.addImage(imgData, 'JPEG', (pageWidth - imgWidth) / 2, 10, imgWidth, imgHeight);// 添加图片到PDF
        pdf.save('test.pdf');// 保存PDF
    })
}
onMounted(() => {
  getcourses()
})
// 跳转到添加课程页面
const handleAddCourse = () => {
  router.push(`/home/Courseupdate`)

}

</script>
<template>
  <div>
    <button v-auth="`update`" @click="handleAddCourse">添加</button>
    <button v-myThrottle="{ delay: 1000, handler: handleClick }">导出图片</button>
    <button v-myThrottle="{ delay: 1000, handler: exportpdf }">导出PDF</button>
    <div style="height: 450px;border: 1px solid red;">
      <div v-if="isLoading">数据加载中...</div>
      <VituaList @delete="handleClickData" :list="courses" ref="virtuaListDOM" v-else></VituaList>
    </div>
    <div v-watermark="`系统内部文件，禁止外传`"></div>
  </div>
</template>



<style scoped></style>